/*****************		全局变量	*****************************/
//保存projecObj对象 域属性，方便后面的对象复制
var propInputArray=['id','projectName','projectSn','investAmount','year','classByProfession',
'classByPhase','classByImportance','departmentNames','departmentIds','designerNames',
'designerPhones','partAName','contactNames','contactPhones','description'];

//项目目录
var contextPath=nsl.getContextPath();

// contract lrGrid Dlg 对象
var lrDgDlgObj=new Object();
lrDgDlgObj.lrDgCallFunction=linkContracts;
lrDgDlgObj.dlgId='div-dlg-lrDgSelect';
lrDgDlgObj.lrDgGridColumns=[[
	                     {'field':'id','title':'id','width':'100','hidden':'true'},
	                     {'field':'contractSn','title':'编号','width':'70'},
	                     {'field':'name','title':'名称','width':'330'}]]; 
lrDgDlgObj.lrDgGridParams={'contactIds':$("#input-contactIds").val(),
							   'partAId':$("#input-partAId").val()};	
lrDgDlgObj.lrDgGridUrl=contextPath+'/contract/getDatagridByFilter';	





// 保存页面selectOption的map 对象 [{'classByPhase':{[{'value':'可研','label':'可研'},{'value':'初步','label':'初步'}]}];
var selectMap=new Object();

//保存页面left_rigth_Dlg 对象 left_right_select left=tree,right=grid
var lrDlg;//easyui dlg 对象.
var lrSelectObj=new Object();//保存left_right_dlg 中的left_right_select 对象
/*var lrDlgQueryParams=new Object();//保存 left_right_dlg 中的查询json对象
lrDlgQueryParams.selectJson='';//lrSelectObj 需要转化为Json字符串形式赋给selectJson
*/

//定义页面中的各种url地址
var urlContractGird=contextPath+'/contract/getDataGridByProjectId';
var urlReleaseContract=contextPath+'/project/releaseWithContract';
var urlDeleteContract=contextPath+'/contract/deleteById';
var urlUpdateRelationWithContract=contextPath+'/project/updateRelationWithContract';
var urlAddTabOfContractDetail='';
var urlDeleteContractPhotoByObj=contextPath+'/contractPhoto/deleteFileByContractPhoto';
var urlSaveContractPhoto=contextPath+'/contractPhoto/saveByContractPhoto';
var urlDeleteContractPhotoByObjArray=contextPath+'/contractPhoto/deleteFileByContractPhotoArray';
var urlSaveContractPhotoByObjArray=contextPath+'/contractPhoto/saveByContractPhotoArray';
var urlRenderContractPhotoModule=contextPath+'/contractPhoto/renderContractPhotoModule';
var urlDeleteByContractPhotoId=contextPath+'/contractPhoto/deleteByContractPhotoId';
var urlGetContractPhotoById=contextPath+'/contractPhoto/getContractPhotoById';
var urlUpdateContractPhotoByObj=contextPath+'/contractPhoto/updateContractPhotoByObj';

//权限参数
$.canDetailContract=true;
$.canReleaseContract=true;
$.canDeleteContract=true;


//EasyUi contractGrid 对象
var contractGrid=new Object();
var contractIds;//根据grid rows中的id

//保存dgGridDlg对象,对应了contract 选择对话框
var lrGridDlg;

//EasyUi contractPhotoUpload dlg 对象
var contractPhotoUploadEzDlg;//合同照片上传对话框
var contractPhotoUploadEzTab;//合同照片上传对话框中tabs
var uploadContractPhotoArray=new Array();

//EasyUI contractPhotoEdit dlg 对象
var contractPhotoEditEzDlg;


//保存页面project信息
var projectObj={"classByImportance":["二","一"],"classByPhase":["二"],"classByProfession":"一、二","contactId":404,"contactName":"王宏军","contactPhone":"18607181107","contractAmount":33.53,"departmentIds":"43","departmentNames":"华中","description":"项目组织无线、电源等专业5人，历时近6个月，完成了3个地市的设计工作。项目新增RNC 1套，扩容RNC 3套；新增基站 253个。\n设计过程中，从网络容量、覆盖、质量等多方面分析网络现状，以用户感知为重点，加大WCDMA网络的建设力度；在对WCDMA网络区域进行网络测试、分析现有WCDMA站点分布的基础上进行基站选址；依据市区、县城、乡镇、重要交通干线等场景特点，解决市区、县城和乡镇的拓展区域及交通干线的弱覆盖，实现新增通车重要交通线的连续覆盖。","designCode":"14001","designerIds":"1707","designerNames":"薛龙来","designerPhones":"","id":2780,"investAmount":3433.43,"partA":"湖北联通","projectName":"2014年中国联通湖北WCDMA网扩容工程","sn":1};
projectObj={
	    "classByImportance": "一般项目",
	    "classByPhase": "可研,初步",
	    "classByPhaseList": [
	        "可研",
	        "初步"
	    ],
	    "classByProfession": "3G/4G宏站（含配套电源）,宽带接入网",
	    "classByProfessionList": [
	        "3G/4G宏站（含配套电源）",
	        "宽带接入网"
	    ],
	    "contactIds": "",
	    "contactNames": "",
	    "contactPhones": "",
	    "contractAmount": 33.53,
	    "departmentIds": "43",
	    "departmentNames": "华中",
	    "description": "111",
	    "designCode": "14001",
	    "designerIds": "1707",
	    "designerNames": "薛龙来",
	    "designerPhones": "",
	    "id": 2780,
	    "investAmount": 3433.43,
	    "partA": "湖北联通",
	    "projectName": "2014年中国联通湖北WCDMA网扩容工程",
	    "projectSn": "14001",
	    "sn": 1,
	    "year": 2014
	};

/*****************		全局函数		*****************************/
// is array
function isArray(object){
    return object && typeof object==='object' &&
            Array == object.constructor;
}

//EasyUI tree 全选和反选:
//参数 selected 为一个对象，其中selected.checked=true 时，treeMenu 为id的树全选，反之亦然
function treeChecked(selected, treeMenu) {
	var roots = $('#' + treeMenu).tree('getRoots');//返回tree的所有根节点数组
	if (selected.checked) {
		for ( var i = 0; i < roots.length; i++) {
			var node = $('#' + treeMenu).tree('find', roots[i].id);//查找节点
			$('#' + treeMenu).tree('check', node.target);//将得到的节点选中
		}
	} else {
		for ( var i = 0; i < roots.length; i++) {
			var node = $('#' + treeMenu).tree('find', roots[i].id);
			$('#' + treeMenu).tree('uncheck', node.target);
		}
	}
}

//src,des:js obj   paramArray: js Array
function copyObject(src,des,paramArray){
	console.log(this);
	$.each(paramArray, function() {
		console.log(src[this]);
		des[this]=src[this];
	});
	console.log(des);
}

//隐藏编辑按钮、信息模块 ，显示编辑模块,注意对于 需要Js生成大量元素的模块，不要随便使用hide,因为需要重新渲染，影响性能
function hideAndShow(hideIdArray,showIdArray){
	$.each(showIdArray, function() {
		console.log(this);
		$("#"+this).css({visibility:'visible'});
		$("#"+this).css({position:'static'});
	});
	
	$.each(hideIdArray, function() {
		console.log(this);
		$("#"+this).css({visibility:'hidden'});
		$("#"+this).css({position:'absolute'});
	});
}

//初始化
function initial(){
				
}

//折叠函数: selfObj 折叠按钮本身 ,contentId:折叠div id
function collapseContent(selfObj,contentId){
	console.log($(selfObj).text());
	console.log($(selfObj).data("iscollapsed")==false);
	console.log(contentId);
	if($(selfObj).data("iscollapsed")){
		$(selfObj).html('&#xe660;');
		console.log("展开");
		$("#"+contentId).show();
		$(selfObj).data("iscollapsed",false);
	}else{
		console.log("折叠");
		$(selfObj).html('&#xe695;');
		$("#"+contentId).hide();
		$(selfObj).data("iscollapsed",true);
	}
}

// dlg 回调函数:根据designer Dlg 返回值，设置 DesignerIdsAndPhones
function setDesignerIdsAndPhones(resultArray){
	console.log("in callFunc");
	console.log(resultArray);
	var phoneArray=new Array();
	var idsArray=new Array();
	var nameArray=new Array();
	$.each(resultArray,function(){
		phoneArray.push(this.phone);
		idsArray.push(this.id);
		nameArray.push(this.name)
	});
	console.log(idsArray);
	console.log(phoneArray);
	console.log(nameArray);
	$("#input-designerIds").val(idsArray.join(","));
	$("#input-designerPhones").textbox('setValue',phoneArray.join(","));
	$("#input-designerNames").textbox('setValue',nameArray.join(","));
}

//dlg 回调函数:根据partA Dlg 返回值，设置 partAid,parAName 和 contact
function setPartAIdAndPartAName(resultArray){
	console.log("in callFunc");
	console.log(resultArray);
	var partANameArray=new Array();
	var partAIdArray=new Array();
	$.each(resultArray,function(){
		partANameArray.push(this.name+"("+this.province+")");
		partAIdArray.push(this.id);
	});
	console.log(partAIdArray);
	console.log(partANameArray);
	$("#input-partAId").val(partAIdArray[0]);
	$("#input-partAName").textbox('setValue',partANameArray[0]);
}


//dlg 回调函数:根据contact Dlg 返回值，设置contactIds,contactNames,contactPhones
function setContactIdsNamesPhones(resultArray){
	console.log(resultArray);
	var contactNameArray=new Array();
	var contactIdIdArray=new Array();
	var contactPhoneArray=new Array();
	$.each(resultArray,function(){
		contactNameArray.push(this.name);
		contactIdIdArray.push(this.id);
		contactPhoneArray.push(this.phone);
	});
	$("#input-contactIds").val(contactIdIdArray.join(','));
	$("#input-contactNames").textbox('setValue',contactNameArray.join(','));
	$("#input-contactPhones").textbox('setValue',contactPhoneArray.join(','));
}

function initialLrDlg(){
	//初始化左右选择Dlg
	lrDlg=$('#div-dlg-lrSelect').dialog({    
	    title: 'My Dialog',    
	    width: 750,    
	    height: 350,    
	    closed: false,    
	    cache: false,    
	    modal: true,
	    closed:true
	   	//queryParams:lrDlgQueryParams,
	   	//method:'post'
	}); 
}

function initialLrGridDlg(){
	//初始化左右选择Dlg
	lrGridDlg=$('#div-dlg-lrDgSelect').dialog({    
	    title: '关联合同',    
	    width:980,    
	    height: 550,    
	    closed: false,    
	    cache: false,    
	    modal: true,
	    closed:true
	   	//queryParams:lrDlgQueryParams,
	   	//method:'post'
	}); 
	//初始化griDlg 内部的对象
	initLrGrid(lrDgDlgObj);
}

//初始化 页面 select option 选项
function initialSelectOption(selectMap){
	//input-year
	var now=new Date();
	var yearOption=new Array();
	for(var i=2010;i<now.getFullYear();i++){
		var yearobj=new Object();
		yearobj.value=i;
		yearobj.label=i+"年";
		console.log(yearobj);
		yearOption.push(yearobj);
		
	}
	//console.log(yearOption);
	$('#input-year').combobox({    
	    valueField:'value',    
	    textField:'label',
	    data:yearOption
	    
	});  
	
	//classByProfession
	var classByProfession=[{'value':'3G/4G宏站（含配套电源）','label':'3G/4G宏站（含配套电源）'},{'value':'宽带接入网','label':'宽带接入网'}];
	classByProfession=selectMap.classByProfessionList;
	$('#input-classByProfession').combobox({    
	    valueField:'value',    
	    textField:'text',
	    data:classByProfession,
	    multiple:true
	    
	}); 
	
	//classByPhase
	var classByPhase=[{'value':'可研','label':'可研'},{'value':'初步','label':'初步'}];
	classByPhase=selectMap.classByPhaseList;
	console.log(classByPhase);
	$('#input-classByPhase').combobox({    
	    valueField:'value',    
	    textField:'text',
	    data:classByPhase,
	    multiple:true
	    
	}); 

	//classByImportance
	var classByImportanceList=[{'value':'一般项目','label':'一般项目'},{'value':'重点项目','label':'重点项目'}];
	classByImportanceList=selectMap.classByImportanceList;
	$('#input-classByImportance').combobox({    
	    valueField:'value',    
	    textField:'text',
	    data:classByImportanceList,
	    multiple:true
	    
	});

	//departmentNames
	var departmentList=[{'value':'一','label':'1111'},{'value':'二','label':'2222'}];
	departmentList=selectMap.departmentList;
	console.log(departmentList);
	$('#input-departmentIds').combobox({    
	    valueField:'value',    
	    textField:'text',
	    data:departmentList,
	    multiple:true,
	    onSelect:function(record){
	    	$('#input-departmentNames').val($('#input-departmentIds').combobox('getText'));
	    },
	    onUnselect:function(record){
	    	console.log("in unselect");
	    	console.log(record);
	    	$('#input-departmentNames').val($('#input-departmentIds').combobox('getText'));
	    }
	});
	
	
	
	$('#input-designerNames').textbox({    
		buttonIcon:'icon-add',
		onClickButton:function(){
			console.log("hit btn");
			//console.log(lrDlg.dialog('options'));
			console.log($("#input-designerIds").val());
			//lrSelectObj.checkedIds='1578,1579';
			lrSelectObj.callFunction=setDesignerIdsAndPhones;
			lrSelectObj.dlgId='div-dlg-lrSelect';
			lrSelectObj.gridColumnList=[[{'field':'departmentName','title':'部门','width':'100'},
			                     {'field':'id','title':'id','width':'100','hidden':'true'},
			                     {'field':'name','title':'姓名','width':'100'}]]; 
			lrSelectObj.treeUrl= contextPath+'/department/treeWithDesigner';
			lrSelectObj.lrDlgQueryParams={'checkedIds':$("#input-designerIds").val()};	
				
			lrDlg.dialog('setTitle','人员选择');
			reloadLrDlg(lrSelectObj);
			//lrDlg.dialog('refresh');
			lrDlg.dialog('open');;
		}
	}); 
	
	$('#input-partAName').textbox({    
		buttonIcon:'icon-add',
		onClickButton:function(){
			console.log("hit btn");
			console.log(lrDlg.dialog('options'));
			//lrSelectObj.checkedIds='1578,1579';
			lrSelectObj.callFunction=setPartAIdAndPartAName;
			lrSelectObj.dlgId='div-dlg-lrSelect';
			lrSelectObj.gridColumnList=[[{'field':'type','title':'单位类别','width':'100'},
			                     {'field':'id','title':'id','width':'100','hidden':'true'},
			                     {'field':'province','title':'省份','width':'100'},
			                     {'field':'name','title':'单位简称','width':'100'}]]; 
			lrSelectObj.treeUrl= contextPath+'/partA/getTreeList';
			lrSelectObj.lrDlgQueryParams={'checkedIds':$("#input-partAId").val()};	
				
			lrDlg.dialog('setTitle','委托单位选择');
			reloadLrDlg(lrSelectObj);
			//lrDlg.dialog('refresh');
			lrDlg.dialog('open');
			lrDlg.panel('move',{'left':0,'right':0});
		}
	}); 
	
	$('#input-contactNames').textbox({    
		buttonIcon:'icon-add',
		onClickButton:function(){
			console.log("hit btn");
			//lrSelectObj.checkedIds='1578,1579';
			lrSelectObj.callFunction=setContactIdsNamesPhones;
			lrSelectObj.dlgId='div-dlg-lrSelect';
			lrSelectObj.gridColumnList=[[{'field':'partAName','title':'所属单位','width':'100'},
			                     {'field':'id','title':'id','width':'100','hidden':'true'},
			                     {'field':'name','title':'姓名','width':'100'},
			                     {'field':'phone','title':'电话','width':'100'}
			                     ]]; 
			lrSelectObj.treeUrl= contextPath+'/contact/getTreeList';
			lrSelectObj.lrDlgQueryParams={'contactIds':$("#input-contactIds").val(),
										   'partAId':$("#input-partAId").val()};	
				
			lrDlg.dialog('setTitle','委托人选择');
			reloadLrDlg(lrSelectObj);
			//lrDlg.dialog('refresh');
			lrDlg.dialog('open');;
		}
	}); 
	
	//初始化description
	$('#input-description').textbox({    
		multiline:true,
		height:100,
		value:projectObj.description
	});
	console.log("end initial");
	
}

// project 对象 赋值给 InfoModule
function project2InfoModule(projectObj){
	//#div-propInfoModule .div-prop-value
	//console.log('project2InfoModule');
	//console.log($('#div-propInfoModule').attr('id'));
	$('#div-propInfoModule .div-prop-value').each(function() {
		//console.log('in each');
		//console.log($(this).attr('id'));
		var idString=$(this).attr('id');
		var fieldName=idString.substring(5,idString.length);
		console.log(fieldName);
		console.log(projectObj[fieldName]);
		$(this).html(projectObj[fieldName]);
		
	});
}

// project 对象 赋值给 inputModule
function project2InputModule(projectObj){
	//form-propInputModule
	$('#form-propInputModule').form('load',projectObj);
}

//增加合同详情页
function addTabWithContractDetail(id,name){
	console.log(id);
	console.log(name);
}


//解除合同和项目的关联
function releaseContract(id){
	console.log('releaseContract('+id+'0');
	var postData={'id':projectObj.id,"contractIds":id};
	$.messager.confirm('确认对话框', '确定解除项目和合同的关联吗？', function(r){
		if (r){
		    // 退出操作;
			$.ajax( {  
			    url:urlReleaseContract,// 跳转到 action  
			    data:postData,  
			    type:'post',  
			    dataType:'json', //预期服务器返回的数据类型。 
			    beforeSend:function(XMLHttpRequest ){
			    	$.messager.progress({
						title : '提示',
						text : '正在处理~'
					});
			    },
			    success:function(obj) {
			    	console.log(obj);
			    	if(obj.success){
			    		//刷洗contract grid
			    		contractGrid.datagrid('reload');
			    	}else{
			    		alert(obj.msg);
			    	}
			    	$.messager.progress('close');
			    },  
			     error : function(data) { 
			    	 //console.log(data);
			    	 $.messager.progress('close');
			    	 alert("服务器错误，请于管理员联系:18639551912。");
			     }  
			});
		}
	});
	
	
}

//彻底删除合同
function deleteContract(id){
	console.log('deleteContract('+id+'0');
	var postData={'id':id};
	$.messager.confirm('确认对话框', '确认彻底删除合同信息?', function(r){
		if (r){
		    // 退出操作;
			$.ajax( {  
			    url:urlDeleteContract,// 跳转到 action  
			    data:postData,  
			    type:'post',  
			    dataType:'json', //预期服务器返回的数据类型。 
			    beforeSend:function(XMLHttpRequest ){
			    	$.messager.progress({
						title : '提示',
						text : '正在处理~'
					});
			    },
			    success:function(obj) {
			    	console.log(obj);
			    	if(obj.success){
			    		//刷洗contract grid
			    		contractGrid.datagrid('reload');
			    	}else{
			    		alert(obj.msg);
			    	}
			    	$.messager.progress('close');
			    },  
			     error : function(data) { 
			    	 //console.log(data);
			    	 $.messager.progress('close');
			    	 alert("服务器错误，请于管理员联系:18639551912。");
			     }  
			});
		}
	});
	
	
}


//打开合同和项目关联的 gridDlg
function openDlgOfSelectContract(){
	console.log("open dlg of contract");

	reloadLrGridDlg(lrDgObj);
	$("#div-dlg-lrDgSelect").dialog('open');
}

// 关联合同 Dlg 回调函数
function linkContracts(rows){
	console.log("linkContracts");
	console.log(rows);
	var rowArray=new Array();
	$.each(rows, function() {
		rowArray.push(this.id);
	});
	var contractIds=rowArray.join(",");
	var postData={"id":projectObj.id,"contractIds":contractIds};
	console.log(contractIds);
	$.ajax( {  
	    url:urlUpdateRelationWithContract,// 跳转到 action  
	    data:postData,  
	    type:'post',  
	    cache:false,  
	    dataType:'json',  
	    beforeSend:function(XMLHttpRequest ){
	    	$.messager.progress({
				title : '提示',
				text : '正在关联合同信息~'
			});
	    },
	    success:function(result) {
	    	contractGrid.datagrid("load");
	    	$.messager.progress('close');
	    },  
	     error : function(data) { 
	    	 //console.log(data);
	    	 $.messager.progress('close');
	    	 alert("关联失败，请于管理员联系:18639551912。");
	     }  
	});
	
}

function getContractIdArray(contractGridObj){
	console.log("in  getContractId");
	console.log(contractGridObj);
	var idArray=new Array();
	var rows=contractGridObj.datagrid('getRows');
	console.log(rows);
	$.each(rows,function(){
		idArray.push(this.id);
	});
	console.log(idArray);
	return idArray;
}

//清空EzTabs
function clearEzTabs(tabObj){
	while((tabObj.tabs('getTab',0))){
		tabObj.tabs('close',0);
	}
}

//初始化contractPhotoUploadTab 
function initContractPhotoUploadEzDlg(){
		//contractPhotoUploadEzDlg=$('#div-contractPhotoUploadDlg').dialog('dialog');
		contractPhotoUploadEzDlg=$('#div-contractPhotoUploadDlg').dialog({    
		title: '合同照片上传',    
		width: 800,    
		//height: 400,    
		closed: true,    
		cache: false,  
		top:20,
		//href: 'get_content.php',    
		modal: true,
		buttons:"#div-contractPhotoUploadDlg-btns",
		onClose:function(){
			clearEzTabs(contractPhotoUploadEzTab);//dlg中的tab全部删除
			uploadContractPhotoArray.length=0;
			
		},
		onOpen:function(){
			
			//$("#div-contractPhotoUploadDlg-module").dialog("move",{top:$(document).scrollTop() + ($(window).height()-250) * 0.5});
		}
	}); 
	contractPhotoUploadEzTab=$('#div-contractPhotoUploadTab').tabs({    
	    border:true,    
	    onSelect:function(title){    
	        console.log(title+' is selected');   
	       //console.log( uploadContractPhotoArray[title]);
	       var index=title.substring(2,title.length);
	       console.log(index);
	       var contractPhoto=uploadContractPhotoArray[index-1];
	       console.log( contractPhoto);
	      
	       var contractArray=contractGrid.datagrid("getRows");
	       
	       //设置contractSn select, 多个合同时为单选，单个合同，直接选好，无合同，关闭
	       if(contractArray.length>0){
	    	   $('#input-contractPhoto-contractSn').combobox({
	    		   valueField:'id',
	    		   textField:'contractSn',
	    		   data:contractArray
	    	   });
	    	   if(contractArray.length==1){
	    		   $('#input-contractPhoto-contractSn').combobox('setValue',contractArray[0].id);
	    	   }
	       }else{
	    	   $('#input-contractPhoto-contractSn').combobox({
	    		   disabled:true,
	    	   });
	       }
	       
	       $('#form-contractUploadDlg').form('load',contractPhoto);
	       //设置contracstSn
	    },
	    onUnselect:function(title,index){ //取消选择时，把页面信息保存到uploadContractPhotoArray
	    		console.log(title+' is unselected');   
		       //console.log( uploadContractPhotoArray[title]);
		       var index=title.substring(2,title.length);
		       console.log(index);
		       var contractPhoto=uploadContractPhotoArray[index-1];
		       var contractPhotoForm=nsl.serializeObject($('#form-contractUploadDlg'));
		       contractPhoto=$.extend(contractPhoto,contractPhotoForm);
		       console.log(contractPhoto);
		       console.log(uploadContractPhotoArray);
	    }
	});  
}

//检查将要保存的uploadContractPhoto 是否存在 contractId 为空的情况
function checkContractPhotoArray(array){
	var result=new Object();
	result.msg='';
	result.success=true;
	console.log(array);
	for(var i=0;i<array.length;i++){
		if(!array[i].contractId && array[i].validate){
			result.msg=result.msg+"照片"+(i+1)+"未选择合同编号.\n";
			result.success=false;
		}
	}
	return result;
}

//
function deleteContractPhoto(contractPhotoId){
	//alert("id= "+contractPhotoId);
	$.messager.confirm('确认','您确认想要删除照片吗？',function(r){    
	    if (r){
	    	var postData={'id':contractPhotoId}
	    	$.ajax( {  
	    	    url:urlDeleteByContractPhotoId,// 跳转到 action  
	    	    data:postData,  
	    	    type:'post',  
	    	    cache:false,  
	    	    dataType:'json',  
	    	    beforeSend:function(XMLHttpRequest ){
	    	    	$.messager.progress({
	    				title : '提示',
	    				text : '正在删除~'
	    			});
	    	    },
	    	    success:function(result) {
	    	    	console.log(result);
	    	    	if(result.success){
	    	    		refreshContractPhotoModule();
	    	    	}else{
	    	    		 alert("数据加载失败，请于管理员联系:18639551912。");
	    	    	}

	    	    	$.messager.progress('close');
	    	    },  
	    	     error : function(data) { 
	    	    	 //console.log(data);
	    	    	 $.messager.progress('close');
	    	    	 alert("数据加载失败，请于管理员联系:18639551912。");
	    	     }  
	    	});
	        //alert('确认删除');    
	    }else{
	    	//
	    	
	    }    
	}); 
	
}

function editContractPhoto(contractPhotoId){
	var postData={'id':contractPhotoId};
	$.ajax( {  
	    url:urlGetContractPhotoById,// 跳转到 action  
	    data:postData,  
	    type:'post',  
	    cache:false,  
	    dataType:'json',  
	    beforeSend:function(XMLHttpRequest ){
	    	$.messager.progress({
				title : '提示',
				text : '正在加载~'
			});
	    },
	    success:function(result) {
	    	console.log(result);
	    	if(result.success){
	    		var contractPhoto=result.object;
	    		console.log(contractPhoto);
	    		var contractArray=contractGrid.datagrid("getRows");
	    		var src=contextPath+contractPhoto.webPath;
	  	       	$('#img-contractPhotoEdit').attr({src:src})
	    		$('#form-contractPhotoEditDlg').form('load',contractPhoto);
	  	       //设置contractSn select, 多个合同时为单选，单个合同，直接选好，无合同，关闭
	  	       if(contractArray.length>0){
	  	    	   $('#input-contractPhotoEdit-contractSn').combobox({
	  	    		   valueField:'id',
	  	    		   textField:'contractSn',
	  	    		   data:contractArray
	  	    	   });
	  	    	   if(contractArray.length==1){
	  	    		   $('#input-contractPhotoEdit-contractSn').combobox('setValue',contractArray[0].id);
	  	    	   }
	  	       }else{
	  	    	   $('#input-contractPhotoEdit-contractSn').combobox({
	  	    		   disabled:true,
	  	    	   });
	  	       }
	    		
	    		
	    		
	    	}else{
	    		 alert("数据加载失败，请于管理员联系:18639551912。");
	    	}

	    	$.messager.progress('close');
	    },  
	     error : function(data) { 
	    	 //console.log(data);
	    	 $.messager.progress('close');
	    	 alert("数据加载失败，请于管理员联系:18639551912。");
	     }  
	});
	contractPhotoEditEzDlg.dialog('open');
	
}

//btn contractPhoto Edit cancel
function cancleContractPhotoEditDlg(){
	contractPhotoEditEzDlg.dialog('close');
}

//btn contractPhoto Edit cancel
function updateContractPhotoEditDlg(){
	var contractPhotoForm=nsl.serializeObject($('#form-contractPhotoEditDlg'));
	console.log(contractPhotoForm);
	contractPhotoForm.id=parseInt(contractPhotoForm.id);
	//合同编号为空，不能保存
	if(!contractPhotoForm.contractId || contractPhotoForm.contractId.trim()==''){
		alert("未选择合同编号。");
		return;
	}
	var postData={'contractPhoto':contractPhotoForm};
	$.ajax({  
	    url:urlUpdateContractPhotoByObj,// 跳转到 action  
	    data:contractPhotoForm,  
	    type:'post',  
	    dataType:'json', //预期服务器返回的数据类型。 
	    traditional: true,
	    success:function(result) {
	    	if(result.success){
	    		console.log("sucess.");
	    		refreshContractPhotoModule();
	    	}else{
	    		console.log("failed.");;
	    	}
	    },  
	     error : function(data) { 
	    	 //console.log(data);
	    	 alert("服务器错误，请于管理员联系:18639551912。");
	     }  
	});
	contractPhotoEditEzDlg.dialog('close');
}


//刷新 contractPhoto module 
function refreshContractPhotoModule(){
	var contractIdArray=getContractIdArray(contractGrid);
	var contractIds=contractIdArray.join(",");
	console.log(contractIds);
	var postData={'contractIds':contractIds};
	
	$.ajax( {  
	    url:urlRenderContractPhotoModule,// 跳转到 action  
	    data:postData,  
	    type:'post',  
	    cache:false,  
	    dataType:'json',  
	    beforeSend:function(XMLHttpRequest ){
	    	$.messager.progress({
				title : '提示',
				text : '正在加载数据~'
			});
	    },
	    success:function(result) {
	    	console.log(result);
	    	if(result.success){
	    		$('#div-contractPhotoBody').html(result.object);
	    	}else{
	    		 alert("数据加载失败，请于管理员联系:18639551912。");
	    	}
	    	$('.btn-contractPhoto').linkbutton({    
	    	    iconCls: 'icon-search'   
	    	});  

	    	$.messager.progress('close');
	    },  
	     error : function(data) { 
	    	 //console.log(data);
	    	 $.messager.progress('close');
	    	 alert("数据加载失败，请于管理员联系:18639551912。");
	     }  
	});
}


//init edit contractPhotoEditDlg module
function initcontractPhotoEditDlg(){
	contractPhotoEditEzDlg=$('#div-contractPhotoEditDlg').dialog({    
		title: '合同照片编辑',    
		width: 800,    
		//height: 400,    
		closed: true,    
		cache: false,  
		top:20,
		//href: 'get_content.php',    
		modal: true,
		buttons:"#div-contractPhotoEdit-btns",
		onClose:function(){
			
		},
		onOpen:function(){
		}
	}); 
}

/*****************		加载页面完成后定义		*****************************/
$(document).ready(function() {
	/*****************	页面初始化		*****************************/	
	
	//加载projectObj对象，初始化prop module
	var postData=new Object();
	$.ajax( {  
	    url:contextPath+"/test/project/initData",// 跳转到 action  
	    data:postData,  
	    type:'post',  
	    cache:false,  
	    dataType:'json',  
	    beforeSend:function(XMLHttpRequest ){
	    	$.messager.progress({
				title : '提示',
				text : '正在加载数据~'
			});
	    },
	    success:function(json) {
	    	console.log(json);
	    	projectObj=json.obj.projectObj;
	    	selectMap=json.obj.selectMap;
	    	console.log(projectObj);
	    	console.log(selectMap);
	    	initialSelectOption(selectMap);
	    	initialLrDlg();
	    	initialLrGridDlg();
	    	initcontractPhotoEditDlg();
	    	initContractPhotoUploadEzDlg();
	    	project2InfoModule(projectObj);
	    	project2InputModule(projectObj);
	    	$('.btn-contractPhoto').linkbutton({    
	    	    iconCls: 'icon-search'   
	    	}); 
	    	$.messager.progress('close');
	    },  
	     error : function(data) { 
	    	 //console.log(data);
	    	 initialLrDlg()
	    	 $.messager.progress('close');
	    	 alert("数据加载失败，请于管理员联系:18639551912。");
	     }  
	});
	
	
	//初始化 contractGrid
	contractGrid=$('#contract-grid').datagrid({    
	   // data: contractGridObj,  
	    url:urlContractGird,
	    fitColumns : true,
	    nowrap : false,
	    striped:true,
	    queryParams:{"projectId":projectObj.id},
	    columns:[[    
	        {field:'id',title:'id',width:70,hidden:true},    
	        {field:'contractSn',title:'编号',width:40},    
	        {field:'name',title:'合同名',width:400},        
	        {field:'date',title:'日期',width:60},        
	        {field:'clientName',title:'委托单位',width:60},        
	        {field:'builderName',title:'建设单位',width:60},        
	        {field:'amount',title:'合同金额',width:50},        
	       /* {field:'performanceStatus',title:'履约情况',width:60},        
	        {field:'isBilling',title:'是否开票',width:60},        
	        {field:'settlementSn',title:'结清编号',width:60}, */   
	        {field : 'action',
			 title : '操作',
			 width : 75,
			 formatter : function(value, row, index) {
					var str = '';
					//详情页
					if ($.canDetailContract) {
						//str += $.formatString('<img onclick="addDesignerDetailTab(\'{0}\',\'{1}\');" src="{2}" title="详情"/>', row.id,row.name, '${pageContext.request.contextPath}/style/images/extjs_icons/book_open.png');
						str += $.formatString('<a title="合同详情" class="easyui-tooltip" href="javascript:void(0);"><span class="iconfont" onclick="addTabWithContractDetail(\'{0}\',\'{1}\');" >&#xe655;</span></a>', row.id,row.name);
					}
					str += '&nbsp;&nbsp;';
					if($.canReleaseContract){
						//str += $.formatString('<img onclick="addDesignerDetailTab(\'{0}\',\'{1}\');" src="{2}" title="详情"/>', row.id,row.name, '${pageContext.request.contextPath}/style/images/extjs_icons/book_open.png');
						str += $.formatString('<a title="解除关联" class="easyui-tooltip" href="javascript:void(0);"><span class="iconfont" onclick="releaseContract(\'{0}\');" >&#xe655;</span></a>', row.id);							
					}
					str += '&nbsp;&nbsp;';
					if ($.canDeleteContract) {
						//str += $.formatString('<img onclick="deleteFun(\'{0}\');" src="{1}" title="删除"/>', row.id, '${pageContext.request.contextPath}/style/images/extjs_icons/cancel.png');
						str += $.formatString('<a title="删除合同" class="easyui-tooltip" href="javascript:void(0);"><span class="iconfont" onclick="deleteContract(\'{0}\');" >&#xe655;</span></a>', row.id);							
					}
					return str;
				}
			}
    ]]   
 });


	
/*****************	prop module 按钮事件绑定		*****************************/
// btn-propEdit: 编辑详情按钮
	$('#btn-propEdit').on('click',function(){
		hideAndShow(['div-propInfoModule','btn-propEdit'],['div-propInputModule']);
	});

// 绑定 btn-propInputModuleCancle 事件
	$('#btn-propInputModuleCancle').on('click',function(){
		console.log("in prop cancle");
		console.log(projectObj);
		project2InputModule(projectObj);
		hideAndShow(['div-propInputModule'],['div-propInfoModule','btn-propEdit']);
	});

// 绑定 btn-propInputModuleReset 事件
	$('#btn-propInputModuleReset').on('click',function(){
		console.log("in prop reset");
		console.log(projectObj);
		project2InputModule(projectObj);
	});

//绑定propInputModule 保存事件
	$('#btn-propInputModuleSave').on('click',function(){
		console.log($(this).attr('id'));
		$('#form-propInputModule').form('submit', {
			url: contextPath+'/project/detail/update',
			ajax:true,
			onSubmit: function(param){
				var isValid = $(this).form('validate');
				
				console.log(param);
				if (!isValid){
					$.messager.alert('消息','输入不合法');
					return false;// hide progress bar while the form is invalid
				}
				$.messager.progress({
					title : '提示',
					text : '更新中~'
				});
				return true;	// return false will stop the form submission
			},
			onBeforeLoad:function(param){
				//console.log('in onBeforeLoad');
				//console.log('in param');
			},
			success:function(data){
				console.log("in submit success.");
				//console.log(data);
				var resultObj=JSON.parse(data);
				//console.log(resultObj);
				if(resultObj.success){
					console.log(resultObj.object);
					copyObject(resultObj.object,projectObj,propInputArray);
					project2InfoModule(projectObj);
					console.log("update success!");
				}else{
					alert("更新数据失败!");
				}
				$.messager.progress('close');	// hide progress bar while submit successfully
				hideAndShow(['div-propInputModule'],['div-propInfoModule','btn-propEdit']);
			},
			onLoadSuccess:function(data){
				//console.log(data);
			}
		});
		
	});
	
	/***************** 绑定	test btn	*****************************/
	$("#test").on("click",function(){
		console.log("hit test btn");
		$('#div-contractPhotoUploadDlg').dialog('center');
	});

	
	/***************** 上传插件绑定	*****************************/
	
	var x=1;
	$("#btn-uploadContractPhoto").on('click',function(){
		console.log("hit btn-uploadContractPhoto");
		contracPhotoUploader.reset();
		contractIdArray=getContractIdArray(contractGrid);
		console.log(contractIdArray);
		if(contractIdArray.length>0){
				x=x+1;
			console.log("x="+x);
			$(".webuploader-element-invisible").click();
		}else{
			alert("未关联合同，无法上传合同照片。")
		}
	
	});
		//产生文件上传器
	var contracPhotoUploader = WebUploader.create({
		 // 选完文件后，是否自动上传。
	    auto: true,
	    // swf文件路径
	    swf: contextPath+"/js/webUpload/Uploader.swf",

	    // 文件接收服务端。
	    server:contextPath+"/contract/uploadContractPhotos",
		
	    //队列中文件数量
	    //fileNumLimit:5,
	    
		//参数，初始化中就固定了，建议修改内部实现，使之成为可变参数
	    formData: {
	       'projectId': projectObj.id,
	       "contractIds":x
	    },
	    
	    pick: {
           id: '#uploadPicker4ContractPhoto',
           multiple:true
           /* label: '点击添加照片'*/
        },

	    accept: {
	        title: 'Images',
	        extensions: 'gif,jpg,jpeg,bmp,png',
	        mimeTypes: 'image/*'
	    }
	});
	
	console.log(WebUploader.Base.version);
	
	//产生错误时的回调函数
	contracPhotoUploader.on('error', function( type ){
	    /* if ( type === 'Q_EXCEED_NUM_LIMIT' ) {
	        alert('最多允许上传5张图片');
	        console.log( contracPhotoUploader.getFiles() );
	        canUpload=false;
	        alert("wait"+canUpload);
	        //contracPhotoUploader.reset();
	    } */
	});
		
	//在一批文件加入队列时触发
	contracPhotoUploader.on( 'filesQueued', function( files ) {
		//alert("in filesQueued");
		//uploadContractPhotoArray.length=0;//初始化
		if(files.length>5){
			alert("一次最多只能上传5个文件!");
			contracPhotoUploader.reset();
		}
		console.log(files);
	});
		
		
	//注册上传事件
	var progressInt=1;
	contracPhotoUploader.on( 'uploadProgress', function( file, percentage ) {
		//console.log("progress=="+progressInt);
		progressInt++;
	});
	
	//注册启动事件
	contracPhotoUploader.on('startUpload',function(){
		
	});
	
	//文件上传结束时
	contracPhotoUploader.on('uploadFinished',function(){
		var i=0;
		console.log(uploadContractPhotoArray);
		if(uploadContractPhotoArray.length>0){
			$.each(uploadContractPhotoArray,function(){
				
				contractPhotoUploadEzTab.tabs('add',{    
				    title:'照片'+(i+1),
				    content:"<div style='width: 380px;height:450px;display:inline-block;'><img class='img-border' src='"+contextPath+this.webPath+"' /></div>",
					});
				i=i+1;
			});
			
			//contractPhotoUploadEzTab.tabs('select',"照片1");
			var position=$(document).scrollTop(0);
			position=position+10;
			console.log('position='+$(document).scrollTop());
			//contractPhotoUploadEzDlg.dialog('center');
			contractPhotoUploadEzDlg.dialog('open');
			
			//contractPhotoUploadEzDlg.window('center');
			//$('#div-contractPhotoUploadDlg').dialog('open');
			//$('#div-contractPhotoUploadDlg').dialog('move',{top:position,left:0});
		}
		console.log("finishe");
		
	});
	
	// 文件上传成功。
	contracPhotoUploader.on( 'uploadSuccess', function( file,response) {
		console.log(file);
		console.log(response);
		var contractPhoto=response.object;
		contractPhoto.validate=true;//记录tab title后缀名的序号
		uploadContractPhotoArray.push(contractPhoto);
	});

	// 文件上传失败
	contracPhotoUploader.on( 'uploadError', function( file ) {
		/*layer.close(projectPhotoIdex);*/
		console.log("upload failed");
	});

	// 完成上传完了，成功或者失败，先删除进度条。
	contracPhotoUploader.on( 'uploadComplete', function( file ) {
		/*layer.close(projectPhotoIdex);*/
		console.log("upload complete");
	});
	
	
	/***************** 保存上传照片对话框中 按钮行为	*****************************/
	$('#btn-contractPhotoDlg-deleteThis').on('click',function(){
		var tab = contractPhotoUploadEzTab.tabs('getSelected');
		var index = contractPhotoUploadEzTab.tabs('getTabIndex',tab);
		var tabCount=contractPhotoUploadEzTab.tabs('tabs').length;
		console.log("delete photo");
		var contractPhoto=uploadContractPhotoArray[index];
		var postData=contractPhoto;
		console.log(contractPhoto);
		$.ajax( {  
		    url:urlDeleteContractPhotoByObj,// 跳转到 action  
		    data:postData,  
		    type:'post',  
		    dataType:'json', //预期服务器返回的数据类型。 
		    success:function(result) {
		    	if(result.success){
		    		console.log(result.object.webPath+" is deleted");
		    	}else{
		    		console.log(result.msg);
		    	}
		    },  
		     error : function(data) { 
		    	 //console.log(data);
		    	 alert("服务器错误，请于管理员联系:18639551912。");
		     }  
		});
		
		//如果只剩一个，关闭dlg,否则只关闭当前
		if(tabCount==1){
			contractPhotoUploadEzDlg.dialog('close');
		}else{
			contractPhotoUploadEzTab.tabs('close',index);
		}
	});
	
	$('#btn-contractPhotoDlg-SaveThis').on('click',function(){
		var tab = contractPhotoUploadEzTab.tabs('getSelected');
		var index = contractPhotoUploadEzTab.tabs('getTabIndex',tab);
		var tabCount=contractPhotoUploadEzTab.tabs('tabs').length;
		//save之前，怎么校验呢？
		console.log("save photo btn");
		var contractPhotoForm=nsl.serializeObject($('#form-contractUploadDlg'));
		var contractPhoto=uploadContractPhotoArray[index];
		contractPhoto=$.extend(contractPhoto,contractPhotoForm);
		contractPhoto.validae=false;
		console.log(contractPhoto);
		
		//合同编号为空，不能保存
		if(!contractPhoto.contractId){
			alert("未选择合同编号。");
			return;
		}
		
		var postData={'contractPhoto':contractPhoto}
		$.ajax( {  
		    url:urlSaveContractPhoto,// 跳转到 action  
		    data:contractPhoto,  
		    type:'post',  
		    dataType:'json', //预期服务器返回的数据类型。 
		    success:function(result) {
		    	if(result.success){
		    		console.log(result.object.webPath+" is saved");
		    		refreshContractPhotoModule();
		    	}else{
		    		console.log(result.object.webPath+" is failed to save.");;
		    	}
		    },  
		     error : function(data) { 
		    	 //console.log(data);
		    	 alert("服务器错误，请于管理员联系:18639551912。");
		     }  
		});
		
		//如果只剩一个，关闭dlg,否则只关闭当前
		if(tabCount==1){
			contractPhotoUploadEzDlg.dialog('close');
		}else{
			contractPhotoUploadEzTab.tabs('close',index);
		}
	});
	
	$('#btn-contractPhotoDlg-deleteAll').on('click',function(){
		console.log("delete all");
		//urlDeleteContractPhotoByObjArray
		console.log(uploadContractPhotoArray);
		var deleteArray=new Array();
		$.each(uploadContractPhotoArray,function(){
			if(this.validate){
				deleteArray.push(this)
			}
		});
		
		var postData={'contractPhotoListJson':JSON.stringify(deleteArray)};
		$.ajax( {  
		    url:urlDeleteContractPhotoByObjArray,// 跳转到 action  
		    data:postData,  
		    type:'post',  
		    dataType:'json', //预期服务器返回的数据类型。 
		    traditional: true,
		    success:function(result) {
		    	if(result.success){
		    		console.log("sucess.");
		    	}else{
		    		console.log("failed.");;
		    	}
		    },  
		     error : function(data) { 
		    	 //console.log(data);
		    	 alert("服务器错误，请于管理员联系:18639551912。");
		     }  
		});
		
		contractPhotoUploadEzDlg.dialog('close');
	});
	
	$('#btn-contractPhotoDlg-SaveAll').on('click',function(){
		console.log("save all");
		
		var tab = contractPhotoUploadEzTab.tabs('getSelected');
		var index = contractPhotoUploadEzTab.tabs('getTabIndex',tab);
		//save之前，怎么校验呢？
		console.log("save photo btn");
		var contractPhotoForm=nsl.serializeObject($('#form-contractUploadDlg'));
		var contractPhoto=uploadContractPhotoArray[index];
		contractPhoto=$.extend(contractPhoto,contractPhotoForm);
		console.log(contractPhoto);
		
		var result=checkContractPhotoArray(uploadContractPhotoArray);
		if(result.success){
			var saveArray=new Array();
			$.each(uploadContractPhotoArray,function(){
				if(this.validate){
					saveArray.push(this);
				}
			});
			var postData={'contractPhotoListJson':JSON.stringify(saveArray)};
			$.ajax( {  
			    url:urlSaveContractPhotoByObjArray,// 跳转到 action  
			    data:postData,  
			    type:'post',  
			    dataType:'json', //预期服务器返回的数据类型。 
			    traditional: true,
			    success:function(result) {
			    	if(result.success){
			    		console.log("sucess.");
			    		refreshContractPhotoModule();
			    	}else{
			    		console.log("failed.");;
			    	}
			    },  
			     error : function(data) { 
			    	 //console.log(data);
			    	 alert("服务器错误，请于管理员联系:18639551912。");
			     }  
			});
			contractPhotoUploadEzDlg.dialog('close');
		}else{
			alert(result.msg);
		}
		
	});
	
	//contractPhotoEdit Dlg btn:cancle
	$("btn-contractPhotoEditDlg-cancle").on('click',function(){
		contractPhotoEditEzDlg.dialog('close');
	});
	
	//contractPhotoEdit Dlg btn:update
	$("btn-contractPhotoEditDlg-cancle").on('click',function(){
		var contractPhotoForm=nsl.serializeObject($('#form-contractUploadDlg'));
		//合同编号为空，不能保存
		if(!contractPhotoForm.contractId){
			alert("未选择合同编号。");
			return;
		}
		var postData={'contractPhoto':contractPhotoForm};
		$.ajax({  
		    url:urlUpdateContractPhotoByObj,// 跳转到 action  
		    data:postData,  
		    type:'post',  
		    dataType:'json', //预期服务器返回的数据类型。 
		    traditional: true,
		    success:function(result) {
		    	if(result.success){
		    		console.log("sucess.");
		    		refreshContractPhotoModule();
		    	}else{
		    		console.log("failed.");;
		    	}
		    },  
		     error : function(data) { 
		    	 //console.log(data);
		    	 alert("服务器错误，请于管理员联系:18639551912。");
		     }  
		});
		contractPhotoEditEzDlg.dialog('close');
	});
	
});





















